import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Router } from '@angular/router';
import { environment } from './../../environments/environment';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {

  constructor(private router: Router) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const authToken = sessionStorage.getItem('token');

    let authReq = req.clone();

    if (req.url.indexOf('login') !== -1) {
      authReq = req.clone({
        url: environment.baseUrl + req.url,
        setHeaders: {
          'content-type': 'application/json'
        },
      });
    } else if (authToken) {
      authReq = req.clone({
        url: environment.baseUrl + req.url,
        setHeaders: {
          'content-type': 'application/json',
          'X-AUTH-TOKEN': authToken
        },
      });
    } else {
      this.router.navigate(['/login']);
    }

    return next.handle(authReq).pipe(
      tap(
        (data) => {
          return data;
        },
        (error) => {
          switch (error.status) {
            case 401:
              this.router.navigate(['/exception/401']);
              break;
            case 404:
              this.router.navigate(['/exception/404']);
              break;
            case 500:
              this.router.navigate(['/exception/500']);
              break;
          }

          if (error.status > 500 || error.status < 600) {
            this.router.navigate(['/exception/500']);
          }
        }
      )
    );
  }
}
